package com.wu.aop;

import com.wu.enums.UserSessionEnum;
import com.wu.pojo.dto.SessionUserDto;
import com.wu.pojo.reqeust.BaseRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class BaseRequestAspect {

    @Autowired
    private HttpServletRequest servletRequest;

    @Before("execution(* com.wu.controller..*.*(..))")
    public Object before(JoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();

        SessionUserDto sessionUserDto = null;
        for (Object arg : args) {
            try {
                BaseRequest baseRequest = (BaseRequest) arg;
                if (sessionUserDto == null) {
                    sessionUserDto = (SessionUserDto) servletRequest.getSession().getAttribute(UserSessionEnum.SESSION_USER_KEY.getKey());
                }
                baseRequest.setCurrentUserId(sessionUserDto.getId());
                baseRequest.setCurrentDepartId(sessionUserDto.getDepartmentId());
            } catch (Exception e) {
            }
        }

        return joinPoint;
    }
}